package com.example.qqviewspringboot.repository;

import com.example.qqviewspringboot.data.Message;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {

    // 根据消息ID列表获取消息
    @Query("SELECT m FROM Message m WHERE m.id IN :ids")
    List<Message> findAllById(@Param("ids") Iterable<Long> ids);

    // 获取指定用户的所有消息（作为发送者或接收者），按时间戳降序排序
    List<Message> findBySenderIdOrRecipientIdOrderByTimestampDesc(Long senderId, Long recipientId);

    // 获取两个用户之间的所有消息，不使用分页
    @Query("SELECT m FROM Message m WHERE " +
            "(m.sender.id = :userId AND m.recipient.id = :friendId) OR " +
            "(m.sender.id = :friendId AND m.recipient.id = :userId) " +
            "ORDER BY m.timestamp ASC")
    List<Message> findByUsers(@Param("userId") Long userId, @Param("friendId") Long friendId);

    // 获取用户的未读消息
    @Query("SELECT m FROM Message m WHERE m.recipient.id = :userId AND m.readStatus = 'UNREAD'")
    List<Message> findUnreadMessagesForUser(@Param("userId") Long userId);

    // 更新消息为已读
    @Modifying
    @Query("UPDATE Message m SET m.readStatus = 'READ' WHERE m.id IN :messageIds")
    void markMessagesAsRead(@Param("messageIds") List<Long> messageIds);

    // 获取指定接收者ID和消息状态的消息
    List<Message> findByRecipientIdAndReadStatus(Long recipientId, Message.ReadStatus readStatus);
}
